<?php


use Drupal\distribution\Entity\DistributionApply;

function _distribution_services_apply($name, $tel, $birthday) {
  try {
    global $user;
    $uid = $user->uid;
    $applies = entity_load('distribution_apply', FALSE, ['uid' => $uid]);
    if (!empty($applies)) {
      $apply = reset($applies);
      if ($apply instanceof DistributionApply) {
        if ($apply->status == 1) {
          return [
            'code' => 1,
            'msg' => '已申请过',
          ];
        }
      }
    }

    if (empty($apply)) {
      $distributionApply = new DistributionApply();
    }
    else {
      $distributionApply = $apply;
      $distributionApply->status = 0;
    }

    $distributionApply->uid = $uid;
    $distributionApply->name = $name;
    $distributionApply->tel = $tel;
    $distributionApply->birthday = $birthday;
    $distributionApply->save();
    return [
      'code' => 0,
      'msg' => 'ok',
      'apply' => $distributionApply,
    ];
  } catch (Exception $e) {
    watchdog_exception(__FUNCTION__, $e);
    return [
      'code' => 1,
      'msg' => '系统错误',
    ];
  }
}
